package com.example.productdataserviceprovider.service.word;

import cn.hutool.core.io.FileUtil;
import com.example.productdataserviceprovider.service.AbstractService;
import com.sun.javafx.logging.JFRInputEvent;
import org.apdplat.word.WordSegmenter;
import org.apdplat.word.segmentation.Word;
import org.springframework.util.StringUtils;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.*;
import java.util.*;

public class WordsServiceImpl extends AbstractService implements  WordsService{
    private List<Map.Entry<String, Integer>> sort(Map<String,Integer> map){
        List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>()
        {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
            {
                //按照value值，从小到大排序
//                return o1.getValue() - o2.getValue();

                //按照value值，从大到小排序
                return o2.getValue() - o1.getValue();

            }
        });
        return list;
    }
    @Override
    public void staticLineWord(String line, Map<String, Integer> results) {
        List<String> words=new ArrayList<>();
        try {
           words=iKSegmenterToList(line);
           for(String word:words){
               Integer count=results.get(word);
               if(count==null)count=new Integer(0);
               count++;
               results.put(word,count);
           }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public  List<String> iKSegmenterToList(String target) throws Exception {
        if (StringUtils.isEmpty(target)){
            return new ArrayList<>();
        }
        List<String> result = new ArrayList<>();
        StringReader sr = new StringReader(target);
        // 关闭智能分词 (对分词的精度影响较大)
        IKSegmenter ik = new IKSegmenter(sr, false);
        Lexeme lex;
        while((lex=ik.next())!=null) {
            String lexemeText = lex.getLexemeText();
            result.add(lexemeText);
        }

        //LOGGER.info("company:{}, iKSegmenterToList:{}", target, JSON.toJSON(result));
        return result;
    }
    @Override
    public Map<String, Integer> staticFileWords(File file, Map<String, Integer> results) {
        BufferedReader reader=null;
        try {
            reader=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            String line=null;
            while((line=reader.readLine())!=null){
                staticLineWord(line,results);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return results;
    }
    public void writerToFile(List<Map.Entry<String, Integer>> datas,File destFile){
//        logger.info("writerToFile.size="+datas.size());
        BufferedWriter writer=null;
        try {
            writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile),"UTF-8"));
            for (Map.Entry s : datas)
            {
                String line=s.getKey()+":"+s.getValue();
                writer.write(line);
                writer.newLine();
            }
            writer.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info("writerToFile..end!");

    }
    public void putAll(Map<String,Integer> finalResults,Map<String,Integer> datas){
        for(Map.Entry<String,Integer> data:datas.entrySet()){
            Integer count=finalResults.get(data.getKey());
            if(count==null){
                count=new Integer(0);
            }
            count=count+data.getValue();
            finalResults.put(data.getKey(),count);
        }
    }
    public static void main(String[] args) throws Exception {
//        String line="稳是大局！中央政治局会议首提\"六保\"";
//        List<Word> words = WordSegmenter.seg(line);
//        for (Word word : words) {
//            System.out.println(word);
//        }
//        System.out.println("==========");
//        List<String> words2=iKSegmenterToList(line);
//        for(String word:words2){
//            System.out.println(word);
//        }
        WordsServiceImpl service=new WordsServiceImpl();
        String dir="D:\\library\\word\\txt";
        File[] files=new File(dir).listFiles();
        Map<String,Integer> finalResults=new HashMap<>();
        for(File file:files){
            String fileName=file.getName();
            String extName=FileUtil.extName(file);
            String destFileName=fileName.replace("."+extName,"-staticResult.txt");
            Map<String,Integer> data=new HashMap<>();
            Map<String,Integer> results=service.staticFileWords(file,data);
            File destFile=new File(file.getParent()+File.separator+destFileName);
            List<Map.Entry<String,Integer>> datas=service.sort(results);
            logger.info("destFile="+destFile.getPath()+",数量:"+datas.size());
            service.writerToFile(datas,destFile);
            service.putAll(finalResults,results);
        }

        File destFile=new File(dir+File.separator+"汇总.txt");
        List<Map.Entry<String,Integer>> datas=service.sort(finalResults);
        logger.info("总量:"+datas.size());
        service.writerToFile(datas,destFile);
    }
}
